import sys
from sympy import *
# from sqlalchemy import *
# from sqlalchemy.engine import create_engine
# from sqlalchemy.schema import *
from word_similarity import WordSimilarity2010
import re
from pyhanlp import *
import time
# import jieba
from . import bad_word,similarity_word,vocabulary,idf_value,idf_value_avg,stop_word,not_similarity_word,local_vocabularys
# 创建语句相似度实例
ws_tool = WordSimilarity2010()

# hanlp添加本地词
CustomDictionary = JClass("com.hankcs.hanlp.dictionary.CustomDictionary")

for local_vocabulary in local_vocabularys:
    CustomDictionary.add(local_vocabulary)

# 答案处理
def answer_deal(answer, flag):
    user_rule = bad_word + r"|[0-9]{1,2}[.]|[\\(,（][0-9]{0,2}分{0,1}[\\),）]|\W"
    right_rule = bad_word + r"|[0-9]{1,2}[.]|（.*?）|[\\(,（][0-9]{0,2}分{0,1}[\\),）]|\W"

    # 当答案中只有标点符号则不做处理，否则清除标点和不规则数据，
    if (re.search(r"\w", answer) != None):
        if flag:
            clean = re.sub(right_rule, " ", answer.replace(r"\N", " "))
        else:
            clean = re.sub(user_rule, " ", answer.replace(r"\N", " "))
    else:
        clean = answer
    # 分词
    arr = [i.word for i in HanLP.segment(clean)]
    # arr = words = jieba.lcut(clean)
    # 过滤空格和停用词
    answer_arr = [x for x in arr if (not re.search(r"\s", x)) and (x not in stop_word)]
    return list(set(answer_arr))


# 获得标准答案中每个词组的权重值
def get_answer_weight(right_answer):
    answer_weight = []
    for word in right_answer:
        if word in vocabulary:
            answer_weight.append(idf_value[vocabulary.index(word)])
        else:
            answer_weight.append(idf_value_avg)
    return answer_weight


# 计算得分
def correct(right, user):
    right_clean = re.sub(r"提示语在|（.*?）|\W", "", right)
    user_clean = re.sub(r"\W", "", user)
    # 简单清洗后的答案，如果相等则直接获得满分。
    if (right_clean != '' and (right_clean == user_clean or
                               (right_clean in similarity_word and user_clean in similarity_word[right_clean]))):
        return 10

    # 答案处理：脏数据去除+分词
    right_answer = answer_deal(right, true)
    user_answer = answer_deal(user, false)

    # 判断用户答案是否为空，为空则直接返回0
    if (len(user_answer) == 0 or user_answer == ''):
        return 0

    # 获取正确答案每个词的权重
    answer_weight = get_answer_weight(right_answer)
    weight_sum = sum(answer_weight)
    # 初始化最终得分，0.5是为了避免toInt时的向下取整
    score = 0.5
    # 计算学生得分
    for right_word in right_answer:
        # 本地相似词flag
        local_flag = right_word in similarity_word
        # 本地不相似词flag
        not_local_flag = right_word in not_similarity_word
        for user_word in user_answer:
            # 关键词的相似度
            similar = ws_tool.similarity(user_word, right_word)
            # 更新本地相似词flag
            new_local_flag = local_flag and (user_word in similarity_word[right_word])
            # 更新本地不相似词的flag
            new_not_local_flag = not_local_flag and (user_word in not_similarity_word[right_word])
            # 如果词相等则直接返回分值，否则（不相似词为否 并且 （相似词或者相似度满足其一））
            if user_word == right_word or ((not new_not_local_flag) and (similar > 0.75 or new_local_flag)):
                score += answer_weight[right_answer.index(right_word)] / weight_sum * 10
                break;

    if score > 10: score = 10
    return score.__int__()


# def main():
    # engine = create_engine('presto://emr-presto-master:9090/hive/dw_temp')
    # mysql_engine = create_engine('mysql+pymysql://root:root@10.30.28.145:3306/dispatch')
    #
    # sql_select = "select *, concat( right_answer, '##-##', user_answer) algo_score "
    # sql_table = "from dw_temp.pmc_cn_question_algo_data_20210929 "
    # sql_where = "where length(user_id) = 16 "
    # sql_where_1 = "and serial_num not in ('sa1516', 'sa1517', 'sa1816', 'sa1416', 'sa1407', 'sa1506', 'sa1417', 'sa1406', 'sa1507') "
    # sql_limit = "limit 10000"
    # sql_load_data = sql_select + sql_table + sql_where + sql_where_1 + sql_limit
    #
    # print("拉取数据...")
    # print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    #
    # df = pd.read_sql(sql_load_data, engine)
    #
    # print("计算得分...")
    # print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    # df['algo_score'] = df['algo_score'].apply(correct)
    # print("已经计算好结果，写入数据库...")
    # print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    #
    # df.to_sql("pmc_cn_algo_correct_20211019", con=mysql_engine, chunksize=10000, if_exists='replace', index=None,
    #           index_label=None, dtype=None, method=None)
    # print("已完成")
    # print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


# def test():
#     line = ("1. 还没有伞  2.一天，荷叶##-##还没有伞   一天，荷叶")
#     print(correct(line))
#
#
# if __name__ == '__main__':
#     main()